import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import sun.text.Utility;

public class GpsWriter {

// public GpsWriter() {}

	public static void writeGpx(GpsTrack track, String fileName) {
		FileWriter outGpx;
		System.out.println("*** Output GPX File: " + fileName);
		try {
			outGpx = new FileWriter(fileName);
			outGpx.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			outGpx.write("<gpx version=\"1.1\" ");
			outGpx.write("creator=\"GPSCleaner - http://www.mapresso.com/gps\" ");
			outGpx.write("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
			outGpx.write("xmlns=\"http://www.topografix.com/GPX/1/1\" ");
			outGpx.write("xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n");

// outGpx.write("<gpx version='1.1' creator='JOSM'
// xmlns='http://www.topografix.com/GPX/1/1'>");

			outGpx.write("<metadata>\n");
			if (!track.meta.name.equals(""))
				outGpx.write(" <name>" + track.meta.name + "</name>\n");
			if (!track.meta.desc.equals(""))
				outGpx.write(" <desc>" + track.meta.desc + "</desc>\n");
			if (!track.meta.author.equals("")) {
				outGpx.write(" <author>\n");
				outGpx.write("  <name>" + track.meta.author + "</name>\n");
				if (!track.meta.email.equals(""))
					outGpx.write("  <email>" + track.meta.email + "</email>\n");
				outGpx.write(" </author>\n");
			}
			if (!track.meta.keywords.equals("")) {
				outGpx.write(" <keywords>" + track.meta.keywords + "</keywords>\n");
			}
// outGpx.write(" <time>" + (new Date()) + "</time>\n");
			outGpx.write(" <time>"
					+ ((Location) track.trackPoints.elementAt(0))
							.getTimeString() + "</time>\n");

			track.doBoundaries();
			outGpx.write("<bounds minlat=\"" + track.lat_min + "\" minlon=\""
					+ track.lon_min + "\" maxlat=\"" + track.lat_max
					+ "\" maxlon=\"" + track.lon_max + "\"/>\n");
			outGpx.write("</metadata>\n");
			outGpx.write("<trk>\n");
			outGpx.write("<trkseg>\n");

			for (int i = 0; i < track.trackPoints.size(); i++) {
				outGpx.write("<trkpt lat=\""
						+ ((Location) track.trackPoints.elementAt(i))
								.getLatitude()
						+ "\" lon=\""
						+ ((Location) track.trackPoints.elementAt(i))
								.getLongitude() + "\">");
				outGpx.write("<ele>"
						+ ((Location) track.trackPoints.elementAt(i))
								.getElevation() + "</ele>");
				outGpx.write("<time>"
						+ ((Location) track.trackPoints.elementAt(i))
								.getTimeString() + "</time>");
				outGpx.write("</trkpt>\n");
			}
			outGpx.write("</trkseg>\n");
			outGpx.write("</trk>\n");
			outGpx.write("</gpx>\n");
			closeFile(outGpx);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	static String makeKml(GpsTrack track) {
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		sb.append("<kml xmlns=\"http://earth.google.com/kml/2.2\">\n");
		sb.append("<Document>\n");
		sb.append("<name>GPS: " + track.meta.name + "</name>\n");
		sb.append("<description>" + track.meta.desc + "</description>\n");
		sb.append("<Style id=\"lineStyle\">\n");
		sb.append("<LineStyle>\n");
		sb.append("<color>6417eeee</color>\n");
		sb.append("<width>4</width>\n");
		sb.append("</LineStyle>\n");
		sb.append("</Style>\n");
		sb.append("<Folder>\n");
		sb.append("<name>Tracks</name>\n");

		sb.append("<Placemark>\n");
		sb.append("<name>Path (" + track.trackPoints.size()
				+ " points)</name>\n");
		sb.append("<styleUrl>#lineStyle</styleUrl>\n");
		sb.append("<LineString>\n");
		sb.append("<tessellate>1</tessellate>\n");
		sb.append("<coordinates>\n");
		for (int i = 0; i < track.trackPoints.size(); i++) {
			sb.append(((Location) track.trackPoints.elementAt(i))
					.getLongitude()
					+ ","
					+ ((Location) track.trackPoints.elementAt(i)).getLatitude()
					+ ","
					+ ((Location) track.trackPoints.elementAt(i))
							.getElevation() + "\n");
		}
		sb.append("</coordinates>\n");
		sb.append("</LineString>\n");
		sb.append("</Placemark>\n");
		sb.append("</Folder>\n");
		sb.append("</Document>\n");
		sb.append("</kml>\n");
		return sb.toString();
	}

	public static void writeKml(GpsTrack track, String fileName, boolean compressed) {
		String str = makeKml(track);
		try {
			if (compressed) {
				System.out.println("*** Output KML File: " + fileName);
				ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
						new FileOutputStream(fileName)));
				zos.setLevel(Deflater.BEST_COMPRESSION);
				PrintStream p = new PrintStream(zos);
				zos.putNextEntry(new ZipEntry(fileName + ".kml"));
				p.println(str);
				p.close();
			} else {
				System.out.println("*** Output KMZ File: " + fileName);
				FileWriter outKml;
				outKml = new FileWriter(fileName);
				outKml.write(str);
				closeFile(outKml);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/*
	 * 
	 * <?xml version="1.0" encoding="UTF-8"?> <kml
	 * xmlns="http://earth.google.com/kml/2.2"> <Document> <name>Paths</name>
	 * <description>Examples of paths. Note that the tessellate tag is by
	 * default set to 0. If you want to create tessellated lines, they must be
	 * authored (or edited) directly in KML.</description> <Style
	 * id="yellowLineGreenPoly"> <LineStyle> <color>7f00ffff</color> <width>4</width>
	 * </LineStyle> <PolyStyle> <color>7f00ff00</color> </PolyStyle> </Style>
	 * <Placemark> <name>Absolute Extruded</name> <description>Transparent
	 * green wall with yellow outlines</description>
	 * <styleUrl>#yellowLineGreenPoly</styleUrl> <LineString> <extrude>1</extrude>
	 * <tessellate>1</tessellate> <altitudeMode>absolute</altitudeMode>
	 * <coordinates> -112.2550785337791,36.07954952145647,2357
	 * -112.2549277039738,36.08117083492122,2357
	 * -112.2552505069063,36.08260761307279,2357
	 * -112.2564540158376,36.08395660588506,2357
	 * -112.2580238976449,36.08511401044813,357
	 * -112.2595218489022,36.08584355239394,357
	 * -112.2608216347552,36.08612634548589,357
	 * -112.262073428656,36.08626019085147,2357
	 * -112.2633204928495,36.08621519860091,2357
	 * -112.2644963846444,36.08627897945274,2357
	 * -112.2656969554589,36.08649599090644,2357 </coordinates> </LineString>
	 * </Placemark> </Document> </kml>
	 * 
	 */

	private static void closeFile(FileWriter f) {
		try {
			f.flush();
			f.close();
		} catch (Exception e) {
			System.out.println("" + e);
			e.printStackTrace();
		}
	}

}
